<script setup>
import { bookCategory } from '@/api/book/index'
import { ref, onMounted, watch } from 'vue'

const props = defineProps({
  modelValue: {
    type: [Number, String, null],
    default: null
  },
  width: {
    type: String,
    default: '100%'
  }
})

const emit = defineEmits(['update:modelValue'])

const channelList = ref([])
const selectedId = ref(props.modelValue)

// 获取分类列表
const getChannelList = async () => {
  try {
    const res = await bookCategory()
    channelList.value = res.data.data
  } catch (error) {
    console.error('获取图书分类失败:', error)
  }
}

// 同步外部传入的 modelValue 到内部变量
watch(() => props.modelValue, (newVal) => {
  selectedId.value = newVal
})

// 同步内部选择到外部 modelValue
watch(selectedId, (newVal) => {
  emit('update:modelValue', newVal)
})

onMounted(() => {
  getChannelList()
})
</script>

<template>
  <el-select
    v-model="selectedId"
    :style="{ width }"
    placeholder="请选择分类"
    filterable
  >
    <el-option
      v-for="item in channelList"
      :key="item.id"
      :label="item.categoryName"
      :value="item.id"
    />
  </el-select>
</template>
